package com.addcn.caruimodule.text;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.TextPaint;
import android.text.style.ReplacementSpan;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.addcn.caruimodule.util.WindowUtil;


/**
 * author:luwenbo
 * created on date : 2019-11-15
 * content:
 * describe:
 */
public class CustomSpan extends ReplacementSpan {
    private int fontSizeSp;
    private Context context;
    public CustomSpan(Context context,int size){
        this.fontSizeSp = size;
        this.context = context;
    }
    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        text = text.subSequence(start, end);
        Paint p = getCustomTextPaint(paint);
        return (int) p.measureText(text.toString());
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        text = text.subSequence(start, end);
        Paint p = getCustomTextPaint(paint);
        Paint.FontMetricsInt fm = p.getFontMetricsInt();
        canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) / 2 - (bottom + top) / 2), p);    //此处重新计算y坐标，使字体居中

    }

    private TextPaint getCustomTextPaint(Paint srcPaint) {
        TextPaint paint = new TextPaint(srcPaint);
        paint.setTextSize(WindowUtil.dp2px(context, fontSizeSp));   //设定字体大小, sp转换为px
        return paint;
    }
}
